package com.huiyeji.hui.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.huiyeji.hui.properties.AliyunOssProperties;
import com.huiyeji.hui.service.AliyunService;
import com.sun.javafx.binding.StringFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zhaoduo
 */
@Service
public class AliyunServiceImpl implements AliyunService {

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    @Override
    public Map<String, String> getPolicyResultMap(){

        String host = StringFormatter.concat("https://",
                                                    aliyunOssProperties.getBucket(),
                                                    ".",
                                                    aliyunOssProperties.getEndpoint()).getValue();

        String dirPrefix = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + UUID.randomUUID().toString().replaceAll("-","");

        Map<String, String> respMap = null;
        try {
            long expireEndTime = System.currentTimeMillis() + aliyunOssProperties.getExpireTime() * 2000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dirPrefix);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<>(6);
            respMap.put("accessid", aliyunOssProperties.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dirPrefix);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }

        return respMap;
    }
}
